<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>销售退货单</title>
<%@ include file="/WEB-INF/pages/common/frameCommonJs.jsp"  %>
<script type='text/javascript' src='<%=request.getContextPath()%>/dwr/engine.js'></script>
<script type='text/javascript' src='<%=request.getContextPath()%>/dwr/util.js'></script>
<script type='text/javascript' src='<%=request.getContextPath()%>/dwr/interface/returnDeliveryVoucherService.js'></script>
<script type='text/javascript' src='<%=request.getContextPath()%>/dwr/interface/searchVoucherService.js'></script>
<style type="text/css">
#fm{
	margin:0;
	padding:10px 30px;
}
.ftitle{
	font-size:14px;
	font-weight:bold;
	color:#666;
	padding:5px 0;
	margin-bottom:10px;
	border-bottom:1px solid #ccc;
}
.fitem{
	margin-bottom:5px;
}
.fitem label{
	display:inline-block;
	width:80px;
}
</style>
<script>
   $(function(){
	  // 已选商品表格
	  $('#selectedPros').datagrid({
		iconCls:'icon-save',
		nowrap: false,
		striped: true,
		collapsible:true,
		url:'<%=request.getContextPath()%>/searchcenter/getProductsByVoucher.action?voucherId=${rdv.id}&searchVoucherCondition.voucherType=returndelivery',
		sortName: 'code',
		sortOrder: 'desc',
		remoteSort: false,
		idField:'code',
		singleSelect:true,
		columns:[[
			{field:'id',title:'id',width:120,edit:false,hidden:true},
			{field:'proNo',title:'编号',width:120,edit:false},
			{field:'name',title:'名称',width:180,edit:false},
			/* {field:'unit',title:'单位',width:120,rowspan:2,sortable:true,
				sorter:function(a,b){
					return (a>b?1:-1);
				}
			,edit:false}, */
			{field:'spec',title:'规格',width:150,rowspan:2,edit:false},
			{field:'unitPrice',title:'退货单价',width:120,editor:'numberbox',editor:{type:'numberbox',options:{precision:2,min:0}},align:'right'},
			{field:'amount',title:'数量',width:120,editor:{type:'numberbox',options:{min:1}},align:'right'},
			{field:'subtotal',title:'小计',width:120,editor:{type:'numberbox',options:{precision:2}},align:'right'},
			{field:'note',title:'备注',width:120,edit:false},
			{field:'action',title:'操作',width:70,align:'center',
                 formatter:function(value,row,index){
                     if (row.editing){
                         var s = '<a href="#" onclick="saverow('+index+')">保存</a> ';
                         var c = '<a href="#" onclick="cancelrow('+index+')">取消</a>';
                         return s+c;
                     } else {
                         var e = '<a href="#" onclick="editrow('+index+')">编辑</a> ';
                         var d = '<a href="#" onclick="deleterow('+index+')">删除</a>';
                         return e+d;
                     }
                 }
             }
		]],
		pageSize:15,  
        pageList:[5,10,15,20],  
        fitColumns: true,  
		rownumbers:true,
		onBeforeEdit:function(index,row){
            row.editing = true;
            $('#selectedPros').datagrid('refreshRow', index);
            editcount++;
        },
        onAfterEdit:function(index,row){
            row.editing = false;
            $('#selectedPros').datagrid('refreshRow', index);
            editcount--;
        },
        onCancelEdit:function(index,row){
            row.editing = false;
            $('#selectedPros').datagrid('refreshRow', index);
            editcount--;
        }
	  });
	  // 初始化，根据单据审核、未审核状态
	  <s:if test='rdv.isverity.toString() == "verityed"'>
	    afterVeriy();
	  </s:if>
	  <s:if test='rdv.isverity.toString() == "cancel"'>
	    afterDel();
	  </s:if>
	  <s:if test='rdv.isverity.toString() == "notverity"'>
	  	$("#id").val(${rdv.id});
	  	afterSave();
	  </s:if>
   });
   var editcount = 0;
   function editrow(index){
   	   $('#selectedPros').datagrid('selectRow',index);
       $('#selectedPros').datagrid('beginEdit', index);
   }
   function deleterow(index){
       $.messager.confirm('确认','是否真的删除?',function(r){
           if (r){
               $('#selectedPros').datagrid('deleteRow', index);
           }
       });
   }
   function saverow(index){
        $('#selectedPros').datagrid('endEdit', index);
        var node = $("#selectedPros").datagrid("getSelected");
        if(node != null){
	      	var subtotal = (node.unitPrice * node.amount).toFixed(2);
	   	    $('#selectedPros').datagrid('updateRow',{
				index: index,
				row: {
					subtotal:subtotal
				}
			});
       }
   }
   function cancelrow(index){
       $('#selectedPros').datagrid('cancelEdit', index);
   }
   function openOrg(){
   		var title = "往来单位选择";
   		$('#orgDlg').dialog('open').dialog('setTitle',title);  
   }
   function openWareHouse(){
   		var title = "退货仓库选择";
   		$('#wareHouseDlg').dialog('open').dialog('setTitle',title);  
   }
   function selectOrg(){
   		var node = $('#orgs').datagrid("getSelected");
   		$("#rdv\\.org\\.name").val(node.name);
   		$("#rdv\\.org\\.id").val(node.id);
   		$('#orgDlg').dialog('close');
   }
   function selectWareHouse(){
   		var node = $('#wars').datagrid("getSelected");
   		$("#rdv\\.wareHouse\\.name").val(node.name);
   		$("#rdv\\.wareHouse\\.id").val(node.id);
   		$('#wareHouseDlg').dialog('close');
   }
   function openSelectPro(){
   		var title = "商品选择";
   		var warehouseid = $("#rdv\\.wareHouse\\.id");
   		var warehousename = $("#rdv\\.wareHouse\\.name");
   		var orgid = $("#rdv\\.org\\.id");
   		if(orgid.val() == ""){
   			$.messager.alert("提示信息:","请先选择往来单位!","warning");
   			orgid.focus();
   			return;
   		}
   		if(warehouseid.val() == ""){
   			$.messager.alert("提示信息:","请先选择仓库!","warning");
   			warehouseid.focus();
   			return;
   		}
   		$('#productsDlg').dialog('open').dialog('setTitle',title);  
   }
   function appendPro(){
   		var node = $("#pros").datagrid("getSelected");
   		var orgId = $("#rdv\\.org\\.id").val();
   		var orgName = $("#rdv\\.org\\.name").val();
   		var whId = $("#rdv\\.wareHouse\\.id").val();
   		var whName = $("#rdv\\.wareHouse\\.name").val();
   		var rows = $('#selectedPros').datagrid('getRows');
   		returnDeliveryVoucherService.verifiyCanReturn(node.id,orgId,whId,function(data){
   			if(data == "no"){
				$.messager.alert("提示信息:","【" + node.name + "】与往来单位【" + orgName +  "】和仓库【" + whName + "】无相关销售记录，不能添加该商品!","warning");
				return;
			}
   			for(var i=0;i<rows.length;i++){
	   			if(rows[i].id==node.id){
	   				$.messager.alert("提示信息:","该商品已经存在!");
	   				return;
	   			}
   			}
	   		$('#selectedPros').datagrid('appendRow',{
	   			id:node.id,
				proNo: node.proNo,
				name: node.name,
				unit:node.unit,
				unitPrice:node.retailPrice.toFixed(2),
				amount:1,
				spec:node.spec,
				note:node.note,
				subtotal:(node.retailPrice * 1).toFixed(2)
			});
   		})
   		
   }
   var searchStockCondition;
   function saveDeliveryVoucher(){
   		var transactionAmount = 0; // 成交金额
		var products = '';
		var rows = $('#selectedPros').datagrid('getRows');
		if(rows.length == 0){
			$.messager.alert("提示信息:","请添加商品!");
			return;
		}
		var orgId = $("#rdv\\.org\\.id").val();
   		var orgName = $("#rdv\\.org\\.name").val();
   		var whId = $("#rdv\\.wareHouse\\.id").val();
   		var whName = $("#rdv\\.wareHouse\\.name").val();
   		var flag = true;
		DWREngine.setAsync(false);
		for(var i=0; i<rows.length; i++){
			saverow(i);
			products += rows[i].id + '_' + rows[i].unitPrice + "_" + rows[i].amount + "_" + rows[i].subtotal + ',';
			searchStockCondition={
				"productId":rows[i].id,
				"orgId":orgId,
				"wareHouseId":whId
			};
			searchVoucherService.getDeliveryNumDWR(searchStockCondition,function(data){
				if(rows[i].amount>data){
					$.messager.alert("提示信息:","商品【" + rows[i].name + "】与往来单位【" + orgName +  "】与仓库【" + whName +  "】销售总数为【<font color='red'>" + data + "</font>】，退货数量不能大于该数字，请修改!","warning");
					flag = false;
					return;
				}
			})
			transactionAmount = parseFloat(rows[i].subtotal) + parseFloat(transactionAmount); // 成交金额计算
		}
		DWREngine.setAsync(true);
		if(flag){
			$('#savelkbt').linkbutton('disable');
			$("#rdv\\.transactionAmount").val(transactionAmount.toFixed(2));
			$("#products").val(products);
			$("#returnDeliveryVoucherFm").form('submit',{
				url:'<%=request.getContextPath()%>/voucher/saveReturnDeliveryVoucher.action',
				onSubmit: function(){  
		            return $(this).form('validate');  
		        },
		        success:function(result){
		        	var result = eval('('+result+')');
		        	$.messager.show({title:"提示信息: ",msg:result.voucherNo + "单据生成成功",showType:'slide'});
		        	afterSave(result);
		        }
			});
		}
	}
	
	// 审核
	function veriyVoucher(){
		var transactionAmount = 0; // 成交金额
		products = '';
		$.messager.confirm('确认','确认审核吗？审核完单据不能再修改',function(r){
			if(r){
				var id = $("#id").val();
				var rows = $('#selectedPros').datagrid('getRows');
				if(rows.length == 0){
					$.messager.alert("提示信息:","请添加商品!");
					return;
				}
				var orgId = $("#rdv\\.org\\.id").val();
		   		var orgName = $("#rdv\\.org\\.name").val();
		   		var whId = $("#rdv\\.wareHouse\\.id").val();
		   		var whName = $("#rdv\\.wareHouse\\.name").val();
				var flag = true;
				DWREngine.setAsync(false);
				for(var i=0; i<rows.length; i++){
					saverow(i);
					products += rows[i].id + "_" + rows[i].unitPrice + "_" + rows[i].amount + "_" + rows[i].subtotal + ",";
					searchStockCondition={
						"productId":rows[i].id,
						"orgId":orgId,
						"wareHouseId":whId
					};
					searchVoucherService.getDeliveryNumDWR(searchStockCondition,function(data){
						if(rows[i].amount>data){
							$.messager.alert("提示信息:","商品【" + rows[i].name + "】与往来单位【" + orgName +  "】与仓库【" + whName +  "】销售总数为【<font color='red'>" + data + "</font>】，退货数量不能大于该数字，请修改!","warning");
							flag = false;
							return;
						}
					})
					transactionAmount = parseFloat(rows[i].subtotal) + parseFloat(transactionAmount); // 成交金额计算
				}
				DWREngine.setAsync(false);
				if(flag){
					$("#veriykbt").linkbutton('disable');
					$("#rdv\\.transactionAmount").val(transactionAmount);
					$("#products").val(products);
					$("#returnDeliveryVoucherFm").form('submit',{
						url:'<%=request.getContextPath()%>/voucher/veriyReturnDeliveryVoucher.action?id=' + id,
						onSubmit: function(){  
				            return $(this).form('validate');  
				        },
				        success:function(result){
				        	var result = eval('('+result+')');
				        	$.messager.show({title:"提示信息: ",msg:result.voucherNo + "单据审核成功",showType:'slide'});
				        	afterVeriy();
				        	$("#newBtn").show();
				        }
					});
				}
			}
		});
	}
	// 保存完毕，页面操作
	function afterSave(result){
		$("#saveBtn").hide();
       	$("#saveVeriy").show();
       	$("#voucherNoSpan").hide();
       	$("#canlBtn").show();
       	<s:if test="rdv==null">
       	$("#id").val(result.id);
       	$("#dv\\.voucherNo").val(result.voucherNo);
       	</s:if>
	}
	// 审核完毕，页面操作
	function afterVeriy(){
		$("#isVeriy").show();
       	$("#saveVeriy").hide();
       	$("#saveBtn").hide();
       	$("#proBtn").hide();
       	$("#canlBtn").hide();
       	$("input").each(function(){
			$(this).attr("readonly","readonly");
		});
		$("#rdv\\.org\\.name").attr("onclick","");
		$("#rdv\\.wareHouse\\.name").attr("onclick","");
		$('#selectedPros').datagrid("hideColumn","action"); // 隐藏操作列
	}
	// 作废完毕，页面操作
	function afterDel(){
		$("#isVeriy").hide();
       	$("#saveVeriy").hide();
       	$("#saveBtn").hide();
       	$("#proBtn").hide();
       	$("#delBtn").show();
       	$("#canlBtn").hide();
       	$("input").each(function(){
			$(this).attr("readonly","readonly");
		});
		$("#rdv\\.org\\.name").attr("onclick","");
		$("#rdv\\.wareHouse\\.name").attr("onclick","");
		$('#selectedPros').datagrid("hideColumn","action"); // 隐藏操作列
		$("#newBtn").show();
	}
	// 作废
	function delVoucher(){
		$.messager.confirm('确认','确认作废吗？作废完单据将不能再修改',function(r){
			if(r){
				var id = $("#id").val();
				$("#returnDeliveryVoucherFm").form('submit',{
					url:'<%=request.getContextPath()%>/voucher/delVoucher.action?id=' + id + '&voucherType=returndelivery',
					onSubmit: function(){  
			            return $(this).form('validate');  
			        },
			        success:function(result){
			        	var result = eval('('+result+')');
			        	$.messager.show({title:"提示信息: ",msg:result.voucherNo + "单据废除成功",showType:'slide'});
			        	afterDel();
			        }
				});
			}
		});
	}
	function newVoucher(){
		parent.newVoucher('销售退货单','<%=request.getContextPath()%>/voucher/toAddReturnDeliveryVoucher.action','icon-voucherin');
	}
</script>
</head>
<body class="easyui-layout" >
<input type="hidden" name="id" id="id" />
<div region="north" title="销售退货单" split="true" style="height:220px;">
	<div id="tb" class="datagrid-toolbar">  
	    <span id="newBtn" style="display:none"><a href="javascript:newVoucher()" class="easyui-linkbutton" iconCls="icon-newvoucher" plain="true" >新单</a></span>
	    <span id="saveBtn"><a href="#" class="easyui-linkbutton" iconCls="icon-save" plain="true" onclick="javascript:saveDeliveryVoucher()" id="savelkbt" name="savelkbt" >保存</a></span>
	    <span id="saveVeriy" style="display:none"><a href="#" class="easyui-linkbutton" iconCls="icon-ok" plain="true" onclick="javascript:veriyVoucher()" id="veriykbt" name="veriykbt">审核</a></span>
	    <span id="isVeriy" style="display:none"><a href="#" class="easyui-linkbutton" iconCls="icon-tip" plain="true" onclick="javascript:veriyVoucher()" disabled><font color="red">已审核</font></a></span>
	    <span id="proBtn" ><a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="javascript:openSelectPro()">添加商品</a></span>
	   <span id="canlBtn" style="display:none"><a href="#" class="easyui-linkbutton" iconCls="icon-cancel" plain="true" onclick="javascript:delVoucher()">作废</a></span>
		 <span id="delBtn" style="display:none"><a href="#" class="easyui-linkbutton" iconCls="icon-tip" plain="true" disabled><font color="red">已作废</font></a></span>
	</div>
	<center>
	<form id="returnDeliveryVoucherFm" method="post">  
	<table style="font-size:12px;padding:10px;0px;0px;0px" border="0">
		<tr>
			<td>往来单位</td>
			<td>
				<input type="text" id="rdv.org.name" name="rdv.org.name" onclick="openOrg()" readonly="readonly" class="easyui-validatebox"  value="${rdv.org.name}" style="PADDING-LEFT: 20px;BACKGROUND-IMAGE: url(<%=request.getContextPath()%>/images/note_add.png); BACKGROUND-REPEAT: no-repeat;cursor:pointer;" size="17" />
				<font color="red">*</font>
				<input type="hidden" id="rdv.org.id" name="rdv.org.id" value="${rdv.org.id}" />&nbsp;&nbsp;
			</td>
			<td>入货仓库</td>
			<td>
				<input type="hidden" id="rdv.wareHouse.id" name="rdv.wareHouse.id" onclick="openWareHouse()" value="${rdv.wareHouse.id}" />
				<input type="text" id="rdv.wareHouse.name" name="rdv.wareHouse.name" onclick="openWareHouse()" readonly="readonly" class="easyui-validatebox" value="${rdv.wareHouse.name}" style="PADDING-LEFT: 20px;BACKGROUND-IMAGE: url(<%=request.getContextPath()%>/images/note_add.png); BACKGROUND-REPEAT: no-repeat;cursor:pointer;" size="17"  />
				<font color="red">*</font>
			</td>
			<td>自定义编号</td>
			<td><input type="text" id="rdv.no" name="rdv.no" class="easyui-validatebox" value="${rdv.no}" maxlength="30"/></td>
		</tr>
		<tr>	
			<td>单据编号</td>
			<td align="left"><input type="text" id="rdv.voucherNo" name="rdv.voucherNo" class="easyui-validatebox"  value="<s:if test="rdv==null">系统生成中...</s:if><s:else>${rdv.voucherNo}</s:else>" disabled="disabled" /></td>
 			<td>成交金额</td>
 			<td><input type="text" id="rdv.transactionAmount" name="rdv.transactionAmount" value="${rdv.transactionAmount}" readonly="readonly" /> <font color="#666666"><b>元</b></font></td>
 		</tr>
		<tr>	
 			<%-- <td>付款金额</td>
 			<td><input type="text" id="rdv.receiveAmount" name="rdv.receiveAmount" class="easyui-numberbox" precision="2" value="<s:if test="wv!=null">${rdv.receiveAmount}</s:if><s:else>0.00</s:else>"  /></td> --%>
 			<s:if test="rdv.user!=null">
 			<td>操作人</td>
			<td><input type="text" id="rdv.user" name="rdv.user" class="easyui-validatebox" value="${rdv.user.name}" disabled="disabled"/></td>
 			</s:if>
 			<s:if test="rdv.datetime!=null">
 			<td>生成时间</td>
			<td><input type="text" id="rdv.datetime" name="rdv.datetime" class="easyui-validatebox" value="<s:date name="rdv.datetime" format="yyyy-MM-dd HH:mm:ss" />" disabled="disabled"/></td>
 			</s:if>
 		</tr>
 		<tr>
 			<td>备注</td>
 			<td colspan="3" align="left"><input type="text" id="rdv.note" name="rdv.note" size="57" value="${rdv.note}"/></td>
 		</tr>
 		<tr>
 			
 		</tr>
 		<input type="hidden" name="products" id="products" />
	</table>
	</form>
	</center>
</div>
<div region="center" title="商品信息" split="true" style="height:350px">
	<table id="selectedPros" name="selectedPros"></table>
</div>
<%@ include file="/WEB-INF/pages/common/organizationSelect.jsp"  %>
<%@ include file="/WEB-INF/pages/common/warehouseSelect.jsp"  %>
<%@ include file="/WEB-INF/pages/common/productSelect.jsp"  %>
</body>
</html>